import os
import json
from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout
from django.core.paginator import Paginator
from django.forms.models import model_to_dict
from django.http.response import JsonResponse
from django.contrib.auth.models import User
from config.default import MEDIA_ROOT, MEDIA_URL, GOVIEW_HTTP_URL
from common.auth import Token, login_exempt
from go_view.models import Projects


# Create your views here.

@login_exempt
def get_oss_info(request):
	return JsonResponse({"msg": "返回成功", "code": 200, "data": {"BucketName": "MEDIA_URL", "bucketURL": GOVIEW_HTTP_URL + MEDIA_URL}})


@login_exempt
def login(request):
	data = json.loads(request.body)
	username = data.get('username')
	password = data.get('password')
	if not username or not password:
		return JsonResponse({'msg': '未知用户名或密码', 'code': 403})
	user = User.objects.filter(username=username).first()
	if not user.check_password(password):
		return JsonResponse({'msg': '密码检查失败', 'code': 403})
	token = Token().create_token(username)
	user_auth = authenticate(request, username=username, password=password)
	auth_login(request, user_auth, )
	
	result = dict(userinfo=dict(id=user.id, username=user.username, nickname=user.first_name), token=dict(tokenName="token", tokenValue=token))
	return JsonResponse({"msg": "操作成功", "code": 200, "data": result})


@login_exempt
def register(request):
	data = json.loads(request.body)
	User.objects.create_user(username=data.get('username'), password=data.get('password'), first_name=data.get('nickname'))
	return JsonResponse({"msg": "注册成功", "code": 200})


@login_exempt
def logout(request):
	auth_logout(request)
	return JsonResponse({"msg": "退出成功", "code": 200})


def create(request):
	data = json.loads(request.body)
	project = Projects.objects.create(**data)
	return JsonResponse({"code": 200, "msg": "创建成功", "data": model_to_dict(project)})


def save_data(request):
	project_id = request.POST.get('projectId')
	content = request.POST.get('content')
	if not project_id or not content:
		return JsonResponse({"code": 500, "msg": "项目数据不合法", "data": {}})
	try:
		project, _res = Projects.objects.update_or_create(defaults={'content': content}, id=project_id)
		return JsonResponse({"code": 200, "msg": "创建成功", "data": model_to_dict(project)})
	except Exception as e:
		return JsonResponse({"code": 500, "msg": str(e)})


def list_view(request):
	page = request.GET.get('page')
	limit = request.GET.get('limit')
	data = list()
	projects = Projects.objects.filter(isDelete=-1)
	paginator = Paginator(projects, limit)
	page_data = paginator.get_page(page)
	for item in page_data.object_list:
		data.append(model_to_dict(item))
	return JsonResponse({"code": 200, "msg": "获取成功", "count": page_data.number, 'data': data})


def edit(request):
	data = json.loads(request.body)
	Projects.objects.filter(id=data.get('id')).update(**data)
	return JsonResponse({"msg": "操作成功", "code": 200})


def delete(request):
	try:
		ids = request.GET.get('ids')
		if isinstance(ids, str):
			ids = [ids]
		Projects.objects.filter(id__in=ids).update(isDelete=1)
		return JsonResponse({"msg": "操作成功", "code": 200})
	except Exception as e:
		return JsonResponse({"msg": str(e), "code": 502})


def publish(request):
	data = json.loads(request.body)
	if not data.get('id') or not data.get('state'):
		return JsonResponse({"msg": "缺少数据", "code": 500})
	try:
		project = Projects.objects.get(id=data.get('id'))
		project.state = data.get('state')
		project.save()
	except Exception as e:
		return JsonResponse({"msg": str(e), "code": 501})
	return JsonResponse({"msg": "操作成功", "code": 200})


@login_exempt
def get_data(request):
	project_id = request.GET.get('projectId')
	project = Projects.objects.get(id=project_id)
	if not project.content:
		return JsonResponse({"msg": "无数据", "code": 200, "data": None})  # 防止无内容数据前端报错
	return JsonResponse({"msg": "获取成功", "code": 200, "data": model_to_dict(project)})


@login_exempt
def upload(request):
	# 获取文件写入本地MEDIA_ROOT目录
	file_object = request.FILES.get('object')
	file_object_name = file_object.name
	file_data = file_object.file.read()
	project_id = file_object_name.split('_')[0]
	file_path = os.path.join(MEDIA_ROOT, file_object_name)
	with open(file_path, 'wb') as fd:
		fd.write(file_data)
	# 更新项目表图片
	project = Projects.objects.get(id=project_id)
	project.indexImage = GOVIEW_HTTP_URL + MEDIA_URL + file_object_name
	project.save()
	result = dict(fileName=file_object_name, id=project_id)
	return JsonResponse({"msg": "获取成功", "code": 200, "data": result})
